package com.xvyy.tingshu.search.runners;

import com.xvyy.tingshu.search.service.impl.ItemServiceImpl;
import org.redisson.api.RBloomFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.List;

/**
 * ClassName: DistributedBloomFilterInitRunner
 * Package: com.xvyy.tingshu.search.runners
 *
 * @Description: Runner + Aware 实现分布式布隆过滤器初始化逻辑
 * 1、实现ApplicationRunner接口，重写run方法
 * 2、实现ApplicationContextAware接口，重写setApplicationContext方法
 * @Author: xvyy
 * @Create: 2025/2/7 - 13:48
 * @Version: v1.0
 */
//@Component
public class DistributedBloomFilterInitRunner implements ApplicationRunner, ApplicationContextAware {

    Logger logger = LoggerFactory.getLogger(DistributedBloomFilterInitRunner.class);

    private ApplicationContext applicationContext;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 1. 从spring容器中获取RBloomFilter对象
        RBloomFilter rBloomFilter = applicationContext.getBean("rBloomFilter", RBloomFilter.class);

        // 2. 从MySQL中找到数据库中所有的albumIdList
        ItemServiceImpl itemService = applicationContext.getBean("itemServiceImpl", ItemServiceImpl.class);
        List<Long> albumInfoIdList = itemService.getAlbumInfoIdList();
        // 3. 将albumIdList添加到RBloomFilter中
        for (Long albumInfoId : albumInfoIdList) {
            rBloomFilter.add(albumInfoId);
        }
        logger.info("分布式布隆过滤器初始化完成，初始化数据量：{}", rBloomFilter.count());

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
